package request;

import model.AuthInfo;
import model.Verifycode;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import worddemo.ScriptEngineTest;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 描述:
 *
 * @Auther: bianjie
 * @Date: 2018/10/20
 */
public class Login {
    public final static String QQ = "3319661457";//3319661457
    public final static String PWD = "ZWXZ7r3uBuDEVgi";//ZWXZ7r3uBuDEVgi
    public final static String pt_local_token = "0.5677827230064161";//随机函数产生
    public final static String APPID = "715030901";

    public final static String UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36";
    public static void main(String[] args) {
        search();
    }

    static Map<String, String> cookies = new HashMap();

    static {
        cookies.put("pt_local_token", pt_local_token);
    }


    public static Cookie[] convertCookie(Map<String, String> cookies){

        Cookie[] httpCookies = new Cookie[cookies.size()];
        int i = 0;
        for(Map.Entry<String,String> e:cookies.entrySet()){

            BasicClientCookie cookie = new BasicClientCookie(e.getKey(), e.getValue());
            cookie.setVersion(0);
            cookie.setDomain("/");   //设置范围
            cookie.setPath("/");
            httpCookies[i] = cookie;
            ++i;
        }

        return httpCookies;
    }

    public static void updateCookies(Map<String, String> newCookies){
        cookies.putAll(newCookies);
    }

    public static void getClientkey(){
        String url = "https://localhost.ptlogin2.qq.com:4301/pt_get_st"
                + "?clientuin="+QQ
                + "&callback=ptui_getst_CB"
                + "&r=0.33491937662161453"
                + "&pt_local_tk="+pt_local_token;
        Connection con = Jsoup.connect(url).ignoreContentType(true)
                .cookies(cookies)
                .header("Referer", "https://xui.ptlogin2.qq.com/cgi-bin/xlogin?appid="+APPID
                        +"&daid=73&pt_no_auth=1&s_url=https%3A%2F%2Fqun.qq.com%2Fmanage.html")
                .header("User-Agent", UserAgent);

        Connection.Response rs = null;
        try {
            rs = con.execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("getClientkey statuscode="+rs.statusCode());
        updateCookies(rs.cookies());
        System.out.println("clientkey="+cookies.get("clientkey"));

    }

    public static String getLoginUrl(){
        getClientkey();
        String clientkey = cookies.get("clientkey");

        String url = "https://ssl.ptlogin2.qq.com/jump"
                + "?clientuin="+QQ
                + "&keyindex=19"
                + "&pt_aid="+APPID
                + "&daid=73"
                + "&u1=https%3A%2F%2Fqun.qq.com%2Fmanage.html"
                + "&pt_local_tk="+ Utils.getPtLocalTk(clientkey)
                + "&pt_3rd_aid=0&ptopt=1&style=40";

        Connection con = Jsoup.connect(url).ignoreContentType(true)
                .cookies(cookies);

        Connection.Response rs = null;
        try {
            rs = con.execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        updateCookies(rs.cookies());
        System.out.println(cookies);

        String body = rs.body();
        int ind_start = body.indexOf("(");
        String content = body.substring(ind_start);
        String[] params = content.split(",");
        String loginurl = params[1].trim().replace("'", "");//验证码
        System.out.println("loginurl="+loginurl);
        return loginurl;
    }

    public static void loginClient(){
        String loginurl = getLoginUrl();
//        Connection con = Jsoup.connect(loginurl).ignoreContentType(true)
//                .cookies(cookies)
//                .header("user-agent", UserAgent);
//        Connection.Response rs = null;
//        try {
//            rs = con.execute();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        System.out.println("login status="+rs.statusCode());
//        System.out.println("3cookies="+rs.cookies());
//        System.out.println("3header="+rs.headers());
//        updateCookies(rs.cookies());


        //全局请求设置
        // 创建cookie store的本地实例
        BasicCookieStore cookieStore = new BasicCookieStore();
        cookieStore.addCookies(convertCookie(cookies));

        // 创建一个HttpClient

        CloseableHttpResponse res = null;


        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultCookieStore(cookieStore).build();



        HttpGet get = new HttpGet(loginurl);

        try {
            res = httpClient.execute(get);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                res.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 获取Cookie
        Map<String, String> newCookies = new HashMap();
        for (Cookie c : cookieStore.getCookies()) {
            if(StringUtils.isNotBlank(c.getValue())){
                newCookies.put(c.getName(), c.getValue());
            }
        }
        System.out.println("newCookies="+newCookies);
        updateCookies(newCookies);

    }

    public static void search(){
        loginClient();

//        AuthInfo authInfo = login();


        String groupNum = "937571366";//937571366
        String key = "297049039";//297049039
        String url4 = "https://qun.qq.com/cgi-bin/qun_mgr/search_group_members";
        Map<String, String> data = new HashMap<>();
        data.put("gc", groupNum);//群号
        data.put("st", "0");
        data.put("end", "20");
        data.put("sort", "0");
        data.put("key", key);//搜索号码
        data.put("bkn", ""+Utils.getBkn(cookies.get("skey")));//2029019042

        Map<String, String> requestHeaders = new HashMap<>();
        requestHeaders.put("user-agent", UserAgent);
        requestHeaders.put("referer", "https://qun.qq.com/member.html");
        requestHeaders.put("x-requested-with", "XMLHttpRequest");
        Connection con = Jsoup.connect(url4).ignoreContentType(true)
                .cookies(cookies)
                .method(Connection.Method.POST)
                .data(data)
                .headers(requestHeaders);
        Connection.Response rs = null;
        try {
            rs = con.execute();
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(rs.body());
    }



    //=================账号密码登录==============
    //2.登录获得cookies
    public static AuthInfo login(){
        Verifycode verifycode = getVerifycode();
        String pwd = ScriptEngineTest.encryptPassword(QQ, PWD, verifycode.getVerifycode());
        String url2 = "http://ptlogin2.qq.com/login?u=3319661457"
                + "&verifycode="+verifycode.getVerifycode()
                + "&pt_vcode_v1=1"
                + "&pt_verifysession_v1="+verifycode.getPt_verifysession_v1()
                + "&p="+pwd
                + "&pt_randsalt=2"
                + "&u1=https%3A%2F%2Fqun.qq.com%2Fmanage.html"
                + "&ptredirect=1&h=1&t=1&g=1&from_ui=1&ptlang=2052"
                + "&action=1-2-1540030425415&js_ver=10284&js_type=1&login_sig=&pt_uistyle=40"
                + "&aid="+APPID
                + "&daid=73";


        System.out.println("url2="+url2);
        Connection con = Jsoup.connect(url2).ignoreContentType(true);
        Connection.Response rs = null;
        try {
            rs = con.execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //ptuiCB('0','0','https://ptlogin2.qun.qq.com/check_sig?pttype=1&uin=3319661457&service=login&nodirect=0&ptsigx=1c9044f4c8c3f31cf905f0373aaa2b4e39958fc05f4fdc05c2d86a8e82fdc0d00bd68e499eb1ae5e0707597e596752caa4cea8d7682d1982e82aae50c4105374&s_url=https%3A%2F%2Fqun.qq.com%2Fmanage.html&f_url=&ptlang=2052&ptredirect=101&aid=715030901&daid=73&j_later=0&low_login_hour=0&regmaster=0&pt_login_type=1&pt_aid=0&pt_aaid=0&pt_light=0&pt_3rd_aid=0','1','登录成功！', 'testin')
        String body = rs.body();
        if(body.contains("登录成功"))
            System.out.println("登录成功");
        else {
            System.out.println("登录失败");
            System.out.println(body);
        }
        Map<String, String> headers = rs.headers();
        Map<String, String> cookies = rs.cookies();

        return new AuthInfo(headers, cookies, body);
    }

    //1.获得验证码
    public static Verifycode getVerifycode() {
        String url1 = "http://check.ptlogin2.qq.com/check?regmaster=&pt_tea=2&pt_vcode=1"
                + "&uin="+QQ+""
                + "&appid="+APPID
                + "&js_ver=10284&js_type=1&login_sig=&u1=https%3A%2F%2Fqun.qq.com%2Fmanage.html"
                + "&r=0.589693430736228&pt_uistyle=40";

        // 第一次请求
//        Connection con = Jsoup.connect(url1);
//        con.header("User-Agent",
//                "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");// 配置模拟浏览器
//        con.header("Content-Type", "application/javascript");
//        Connection.Response rs = con.execute();// 获取响应

        Connection con = Jsoup.connect(url1).ignoreContentType(true);
        Connection.Response rs = null;
        try {
            rs = con.execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //ptui_checkVC('0','!QLM','\x00\x00\x00\x00\xc5\xde\x03\x91','516cadba1399b19904b4db1c18327956daef3bd6127522107a3225a1153be8d3b8badfbf9853a59a093e1cbc8c7814f14432b1d04ca7c557','2')
        String body = rs.body();
        int ind_start = body.indexOf("(");
        String content = body.substring(ind_start);
        String[] params = content.split(",");
        String verifycode = params[1].trim().replace("'", "");//验证码
        String pt_verifysession_v1 = params[3].trim().replace("'", "");//
        System.out.println("verifycode="+verifycode);
        System.out.println(pt_verifysession_v1);
        return new Verifycode(verifycode, pt_verifysession_v1);



    }

}
